var enemyShips = new Array();
var alliedShips = new Array();
var hits = new Array();
var playersShipArray = new Array();
var turn = false;
var rotation =true;
var enemySankShipCount =0;
var playerSankShipCount =0;
function ship(divArray, undropArray, direction, src) {
	this.coordinates = divArray;
	this.undropCoordinates = undropArray;
	this.isShot = false;
	this.health = this.coordinates.length;
	this.src = src;
	this.direction = direction;

}

function getShipAmountCounter(elem) {
	var x = parseInt($("#" + elem + ".div-table-col").html());
	return x;

}
function setShipAmountCounter(elem) {
	var x = parseInt($("#" + elem + ".div-table-col").html());
	x -= 1;
	$("#" + elem + ".div-table-col").html(x);
}

function clearDivs(divArray) {
	for ( var int = 0; int < divArray.length; int++) {
		$('#' + divArray[int]).html('<img class="theImg" src="noimage');
	}

}
function lockShips() {
	$('img').draggable("option", "disabled",true);
	rotation = false;
}

function checkIfReady() {
	if(shipCounter==4){
		$('#btn.myBox').css({
			"background-color": "#7B7B7B"
		});
		$('#btn').attr("disabled", 'disabled');
		$("#chat").fadeOut(0);
		$("#chat").html("<p>You may start shooting.</p>");
		$("#chat").fadeIn(1000);
		lockShips();
		
		decideWhoseTurnIsIt();
		if (turn) {
			oppponentsTurn();
		}
		$('#table2').find('div').addClass("notClicked");

	}
	else{
		console.log('asadas');
		$("#chat").fadeOut(0);
		$("#chat").html("<p>You haven't placed all of the ships yet.</p>");
		$("#chat").fadeIn(1000);
		
	}
}


function opponentStrike(targetId) {

	var target = $('#' + targetId).data("ship");
	if ($('#' + targetId).attr("isClicked")) {

		if (target != undefined && $('#' + targetId).data("ship").health > 0 && !checkForWinner()) {
			target.isShot = true;
			target.health--;
			$('#' + targetId).attr("isClicked", true);
			// console.log($('#' + targetId).data("ship").health);

			$('#' + targetId).prepend(
					'<img class="missOpponent" src="images/hit.gif"/>');

			if ($('#' + targetId).data("ship").health == 0) {
				playerSankShipCount++;
				clearDivs($('#' + targetId).data("ship").coordinates);
				if (target.direction) {
					$('#' + $('#' + targetId).data("ship").coordinates[0])
							.html(
									'<img class="missOpponent" src="images/'
											+ $('#' + targetId).data("ship").coordinates.length
											+ 'pointK.png" />');
				} else {
					$('#' + $('#' + targetId).data("ship").coordinates[0])
							.html(
									'<img class="missOpponent" src="images/'
											+ $('#' + targetId).data("ship").coordinates.length
											+ 'pointRK.png" />');
				}

			}
		} else {
			
			$('#' + targetId).html(
					'<img class="missOpponent" src="images/miss.png" />');
		}
		checkForWinner();
	}
	

}

function strike(targetId) {
	var target = $('#' + targetId).data("ship");
	if ($('#' + targetId).attr("class") == "notClicked") {
		$('#' + targetId).attr("class", "clicked");
		if (target != undefined && $('#' + targetId).data("ship").health > 0 && !checkForWinner()) {
			target.isShot = true;
			target.health--;
			
			// console.log($('#' + targetId).data("ship").health);

			$('#' + targetId)
					.html('<img class="theImg" src="images/hit.gif"/>');

			if ($('#' + targetId).data("ship").health == 0) {
				enemySankShipCount++;
				clearDivs($('#' + targetId).data("ship").coordinates);
				if (target.direction) {
					console.log(target.direction + "buu");
					$('#' + $('#' + targetId).data("ship").coordinates[0])
							.html(
									'<img class="missOpponent" src="images/'
											+ $('#' + targetId).data("ship").coordinates.length
											+ 'pointK.png" />');
				} else {
					$('#' + $('#' + targetId).data("ship").coordinates[0])
							.html(
									'<img class="missOpponent" src="images/'
											+ $('#' + targetId).data("ship").coordinates.length
											+ 'pointRK.png" />');
				}
				

			}
		} else {
			if(!checkForWinner()){
			$('#' + targetId).prepend(
					'<img class="theImg" src="images/miss.png"><img/>');
			}
		}
		if(!checkForWinner()){
			oppponentsTurn();
		}
	}

}

function checkForWinner() {
	if(enemySankShipCount==10){
		$("#chat").fadeOut(0);
		
		$("#chat").html("<p>You have won! Congratulations!</p>");
		
		$("#chat").fadeIn(1000);
		return true;
	}
	else if(playerSankShipCount==10){
		$("#chat").fadeOut(0);
		$("#chat").html("<p>You have lost! Sorry..</p>");
		$("#chat").fadeIn(1000);
		return true;
	}
	else{
		return false;
	}
}

function consist(array, elem) {
	for ( var i = 0; i < array.length; i++) {
		if(elem==array[i]){
			return true;
		}
	}
	return false;
}

function oppponentsTurn() {
	var shipId;
	
	do {
		shipId = 'id' + Math.floor(Math.random() * 100);
	} while (consist(hits,shipId));
	
	
	console.log("COMP SHOOTING: "+shipId);
	
	hits.push(shipId);
	console.log("HITS: "+hits);
	opponentStrike(shipId);
	
}

function decideWhoseTurnIsIt() {
	var turnNum = Math.floor(Math.random() * 2);

	if (turnNum == 0) {
		turn = true;
	} else {
		turn = false;
	}
}

function placeEnemyShips() {
	placeSizeOneShips();
	placeSizeTwoShips();
	placeSizeThreeShips();
	placeSizeFourShips();
}

function createNewShip(element, target) {

	var src = element.attr('src');
	var len = parseInt(element.attr('alt').replace("Ship", ''));

	var first = parseInt(target.attr('id').replace('id', ''));

	var ar = new Array();
	var undropAr = new Array();

	var dir = true;
	if (src.match(/R/)) {
		dir = false;
	}

	for ( var i = 0; i < len; i++) {
		if (dir) {
			ar[i] = 'id' + (first + i);

			var a = [ first + i, first + i - 10, first + i + 10 ];

			for ( var j = 0; j < a.length; j++) {
				if (a[j] > -1 && a[j] < 100) {
					undropAr.push('id' + a[j]);
				}
			}

		} else {
			ar[i] = 'id' + (first + i * 10);

			var a = [ first + i * 10, first + i * 10 - 1, first + i * 10 + 1 ];

			for ( var j = 0; j < a.length; j++) {
				if (a[j] > -1 && a[j] < 100) {
					undropAr.push('id' + a[j]);
				}
			}

		}
	}

	var last = parseInt(ar[ar.length - 1].replace('id', ''));

	if (dir) {
		var a = [ first - 11, first - 1, first + 9, last - 9, last + 1,
				last + 11 ];

		for ( var i = 0; i < a.length; i++) {

			if (a[i] > -1 && a[i] < 100) {
				undropAr.push('id' + a[i]);
			}
		}
	} else {
		var a = [ first - 11, first - 10, first - 9, last + 9, last + 10,
				last + 11 ];

		for ( var i = 0; i < a.length; i++) {
			if (a[i] > -1 && a[i] < 100) {
				undropAr.push('id' + a[i]);
			}
		}
	}

	var left = new Array();
	var right = new Array();

	for ( var i = 0; i < 10; i++) {
		left[i] = 'id' + (i * 10);
		right[i] = 'id' + (9 + 10 * i);
	}
	for ( var i = 0; i < left.length; i++) {
		if (left[i] == ('id' + first)) {
			for ( var z = 0; z < undropAr.length; z++) {
				for ( var k = 0; k < right.length; k++) {
					if (undropAr[z] == right[k]) {
						removeByIndex(undropAr, z);

					}
				}
			}
			break;
		}
	}

	for ( var i = 0; i < right.length; i++) {
		if (right[i] == ('id' + first) || right[i] == ('id' + last)) {
			for ( var z = 0; z < undropAr.length; z++) {
				for ( var k = 0; k < left.length; k++) {
					if (undropAr[z] == left[k]) {
						removeByIndex(undropAr, z);

					}
				}
			}
			break;
		}
	}

	var newship = new ship(ar, undropAr, dir, src);
	$('#' + ar[0]).data("ship", newship);
	playersShipArray.push(newship);
	// console.log("Array :" + playersShipArray[0].undropCoordinates);

	makeUndroppableCells(undropAr);
	PopulateDivs(newship);

	// console.log($('#' + ar[0]).data('ship'));

}

function makeUndroppableCells(array) {
	for ( var i = 0; i < array.length; i++) {
		$('#' + array[i]).droppable("disable");
	}
}
function makeDroppableCells(array) {
	for ( var i = 0; i < array.length; i++) {
		$('#' + array[i]).droppable("enable");
	}
}



function removeByElement(arrayName, arrayElement) {
	for ( var i = 0; i < arrayName.length; i++) {
		if (arrayName[i] == arrayElement)
			arrayName.splice(i, 1);
	}
}

function restoreCells() {

	for ( var i = 0; i < playersShipArray.length; i++) {
		makeUndroppableCells(playersShipArray[i].undropCoordinates);
	}

}

function removeShip(id) {
	// console.log(playersShipArray.length);
	removeByElement(playersShipArray, $("#" + id).data("ship"));
	
	makeDroppableCells($("#" + id).data("ship").undropCoordinates);
	 console.log($("#" + id).data("ship").coordinates.length);
	 var k =$("#" + id).data("ship").coordinates;
	for ( var i = 0; i < k.length; i++) {
		$("#"+k[i]).removeData("ship");
	}
	//$("#" + id).removeData("ship");
	restoreCells();

}

function removeByIndex(arrayName, arrayIndex) {
	arrayName.splice(arrayIndex, 1);
}

function placeSizeOneShips() {
	var shipOne = new ship(new Array("enemyId11"));
	$('#' + shipOne.coordinates[0]).data("ship", shipOne);

	var shipTwo = new ship(new Array("enemyId15"));
	$('#' + shipTwo.coordinates[0]).data("ship", shipTwo);

	var shipThree = new ship(new Array("enemyId18"));
	$('#' + shipThree.coordinates[0]).data("ship", shipThree);

	var shipFour = new ship(new Array("enemyId55"));
	$('#' + shipFour.coordinates[0]).data("ship", shipFour);

	$('#table2').find('div').click(function(event) {
		strike($(this).attr('id'));

	});
	
	$('#table').find('div').attr("isClicked", false);
	// bind('click',strike(event.target.id));

}

function PopulateDivs(shipObject) {
	// console.log(shipObject + "1");
	for ( var int = 0; int < shipObject.coordinates.length; int++) {
		$('#' + shipObject.coordinates[int]).data("ship", shipObject);
	}
}

function placeSizeTwoShips() {
	var shipTwoOne = new ship(new Array("enemyId63", "enemyId64"), [], true);
	var shipTwoTwo = new ship(new Array("enemyId71", "enemyId81"), [], false);
	var shipTwoThree = new ship(new Array("enemyId88", "enemyId98"), [], false);
	console.log(+shipTwoThree.direction);

	PopulateDivs(shipTwoOne);
	PopulateDivs(shipTwoTwo);
	PopulateDivs(shipTwoThree);
	// bind('click',strike(event.target.id));

}

function placeSizeThreeShips() {
	var shipTwoOne = new ship(new Array("enemyId37", "enemyId47", "enemyId57"),
			[], false);
	var shipTwoTwo = new ship(new Array("enemyId76", "enemyId86", "enemyId96"),
			[], false);
	PopulateDivs(shipTwoOne);
	PopulateDivs(shipTwoTwo);
}

function placeSizeFourShips() {
	var shipTwoOne = new ship(new Array("enemyId31", "enemyId32", "enemyId33",
			"enemyId34"), [], true);
	PopulateDivs(shipTwoOne);
}